package com.kc.sys.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kc.sys.common.Constast;
import com.kc.sys.common.DataGridView;
import com.kc.sys.common.GetHanziInitials;
import com.kc.sys.common.R;
import com.kc.sys.domain.Station;
import com.kc.sys.domain.Loginfo;
import com.kc.sys.domain.Role;
import com.kc.sys.domain.User;
import com.kc.sys.service.StationService;
import com.kc.sys.service.LoginfoService;
import com.kc.sys.service.RoleService;
import com.kc.sys.service.UserService;
import com.kc.sys.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 老杜
 * @since 2019-10-16
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StationService deptService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private LoginfoService loginfoService;

    //用户全查询
    @RequestMapping("loadAllUser")
    public DataGridView loadAllUser(UserVo userVo){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        IPage<User> page = new Page<>(userVo.getPage(),userVo.getLimit());
        queryWrapper.eq("type",Constast.USER_TYPE_MORMAL);
        queryWrapper.like(StringUtils.isNotBlank(userVo.getName()),"name",userVo.getName());
        queryWrapper.like(StringUtils.isNotBlank(userVo.getAddress()),"address",userVo.getAddress());
        queryWrapper.eq(userVo.getDeptid()!=null,"deptid",userVo.getDeptid());
        queryWrapper.orderByAsc("ordernum").orderByAsc("hiredate");
        userService.page(page, queryWrapper);
        List<User> records = page.getRecords();
        for (User user : records) {
            Integer deptid = user.getDeptid();
            if(deptid!=null){
                Station dept = deptService.getById(deptid);
                user.setDeptname(dept.getTitle());
            }
            Integer mgr = user.getMgr();
            if(mgr!=null){
                User one = userService.getById(mgr);
                user.setLeadername(one.getName());
            }
        }
        return new DataGridView(page.getTotal(),records);
    }
    //查询最大排序码
    @RequestMapping("loadUserMaxOrderNum")
    public Map<String,Object> loadUserMaxOrderNum(){

        Map<String ,Object> map = new HashMap<>();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.orderByDesc("ordernum");
        List<User> list = userService.list(userQueryWrapper);
        if(list.size()>0){
            map.put("ordernum",list.get(0).getOrdernum()+1);
        }else {
            map.put("ordernum",1);
        }
        return map;
    }
    //根据部门Id查询部门下面的人员
    @RequestMapping("loadUserByDeptId")
    public DataGridView loadUserByDeptId(Integer deptid){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq(deptid!=null,"deptid",deptid);
        userQueryWrapper.eq("available",Constast.AVAILABLE_TRUE);
        userQueryWrapper.eq("type",Constast.USER_TYPE_MORMAL);
        List<User> list = userService.list(userQueryWrapper);
        return new DataGridView(list);
    }
    //将用姓名转成拼音
    @RequestMapping("changeChineseToPinYin")
    public Map<String , Object> changeChineseToPinYin(String username){
        HashMap<String, Object> map = new HashMap<>();
        if(username!=null){
            map.put("loginname",GetHanziInitials.getPingYin(username));
        }else {
            map.put("loginname","");
        }
        return map;
    }

    @RequestMapping("addUser")
    public R addUser(UserVo userVo){
        try {
            userVo.setType(Constast.USER_TYPE_MORMAL);
            userVo.setHiredate(new Date());
            String salt = IdUtil.simpleUUID().toUpperCase();
            userVo.setSalt(salt);//设置盐
            String pwd = new Md5Hash(Constast.USER_DEFAULT_PWD, salt, 2).toString();
            userVo.setPwd(pwd);//设置密码
            userService.save(userVo);
            return R.ok().message("添加成功");
        }catch (Exception e){
             e.printStackTrace();
             return R.error().message("添加失败");
        }

    }

    //根据领导Id查询领导部门Id
    @RequestMapping("loadUserById")
    public DataGridView loadUserById(Integer id){
        User user = userService.getById(id);
        return new DataGridView(user);
    }

    //更新用户的方法
    @RequestMapping("updateUser")
    public R updateUser(UserVo userVo){
        try {
            userService.updateById(userVo);
            return R.ok().message("更新成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("更新失败");
        }
    }

    //删除用户的方法
    @RequestMapping("deleteUser")
    public R deleteUser(Integer id){

        try {
            userService.removeById(id);
            return R.ok().message("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("删除失败");
        }
    }
    //重置用户密码
    @RequestMapping("restPwd")
    public R restPwd(Integer id){

        try {
            User user = new User();
            user.setId(id);
            String salt = IdUtil.simpleUUID().toUpperCase();
            user.setSalt(salt);//设置盐
            String pwd = new Md5Hash(Constast.USER_DEFAULT_PWD, salt, 2).toString();
            user.setPwd(pwd);//设置密码
            userService.updateById(user);
            return R.ok().message("重置成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("重置失败");
        }
    }
    //校验修改密码时旧密码是否正确
    @RequestMapping("changePwd")
    public Map<String,Object> changePwd(Integer id,String newPwd){
        User olduser = userService.getById(id);
        String printpwd = new Md5Hash(newPwd, olduser.getSalt(), 2).toString();
        HashMap<String, Object> map = new HashMap<>();
        if(printpwd.equals(olduser.getPwd())){
            map.put("data","1");
        }else {
            map.put("data","0");
        }
        System.out.println(printpwd+"。。。新密码");
        System.out.println(olduser.getPwd()+"。。。旧密码");
        return map;
    }
    //修改密码
    @RequestMapping("changeOldPwd")
    public R changeOldPwd(Integer id, String pwd){
        try {
            User user = userService.getById(id);
            String newpwd = new Md5Hash(pwd, user.getSalt(), 2).toString();
            user.setPwd(newpwd);
            userService.updateById(user);
            return R.ok().message("密码修改成功！");
        }catch (Exception e){
            e.printStackTrace();
            return R.ok().message("密码修改失败！");
        }
    }
    //根据用户Id查询角色并选中已拥有的角色
    @RequestMapping("initRoleByUserId")
    public DataGridView initRoleByUserId(Integer uid){
        System.out.println("id:"+uid);
        //查询所有可用的角色
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("available",Constast.AVAILABLE_TRUE);
        List<Map<String, Object>> maps = roleService.listMaps(queryWrapper);
        
        //查询当前用户拥有的角色
       List<Integer> currenUserRoleIds = roleService.queryUserRoleIdsByUid(uid);
        for (Map<String, Object> map : maps) {
            Boolean LAY_CHECKED = false;
            Integer roleId = (Integer) map.get("id");
            for (Integer rid : currenUserRoleIds) {
                if(rid == roleId){
                    LAY_CHECKED = true;
                    break;
                }
            }
            map.put("LAY_CHECKED",LAY_CHECKED);
        }
        return new DataGridView((long) maps.size(),maps);
    }
    //为用户分配角色
    @RequestMapping("saveUserRole")
    public R saveUserRole(Integer uid,Integer[] ids){
        try {
            userService.saveUserRole(uid,ids);
            return R.ok().message("分配成功");

        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("分配失败");
        }

    }

    //查询用户登录次数
    @RequestMapping("loadUser")
    public DataGridView loadUser(){
        HashMap<String, Object> map = new HashMap<>();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.ne("id",1);
        List<User> list = userService.list(userQueryWrapper);
        ArrayList<String> usernames = new ArrayList<>();
        ArrayList<Map<String,String>> count = new ArrayList<>();
        for (User user : list) {
            usernames.add(user.getName());
            QueryWrapper<Loginfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("loginname", user.getName());
            List<Loginfo> loginfos = loginfoService.list(queryWrapper);
            HashMap<String, String> map1 = new HashMap<>();
            map1.put("value",loginfos.size()+"");
            map1.put("name",user.getName());
            count.add(map1);
        }
        map.put("count",count);
        map.put("username",usernames);
        return new DataGridView(map);
    }
}

